package org.chen.newsapi.util;

import org.springframework.stereotype.Component;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

@Component
public class HtmlContentProcessor {
    
    // 各种正则表达式模式
    private static final Pattern IMG_PATTERN = Pattern.compile("<img\\s+([^>]*?)>", Pattern.CASE_INSENSITIVE);
    private static final Pattern SRC_PATTERN = Pattern.compile("src\\s*=\\s*[\"']([^\"']*)[\"']", Pattern.CASE_INSENSITIVE);
    private static final Pattern SCRIPT_PATTERN = Pattern.compile("<script[^>]*>.*?</script>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    private static final Pattern STYLE_PATTERN = Pattern.compile("<style[^>]*>.*?</style>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    private static final Pattern DANGEROUS_ATTRS_PATTERN = Pattern.compile("on\\w+\\s*=\\s*[\"'][^\"']*[\"']", Pattern.CASE_INSENSITIVE);
    private static final Pattern EMPTY_TAGS_PATTERN = Pattern.compile("<(p|div|span|h[1-6])\\s*>\\s*</\\1>", Pattern.CASE_INSENSITIVE);
    private static final Pattern MULTI_BR_PATTERN = Pattern.compile("(<br\\s*/??>\\s*){3,}", Pattern.CASE_INSENSITIVE);
    
    /**
     * 处理文章HTML内容，优化移动端显示
     */
    public String processHtmlContent(String originalContent) {
        if (originalContent == null || originalContent.trim().isEmpty()) {
            return "<p>暂无内容</p>";
        }
        
        String content = originalContent;
        
        // 1. 清理危险内容
        content = removeDangerousContent(content);
        
        // 2. 优化图片标签
        content = optimizeImages(content);
        
        // 3. 处理段落和换行
        content = optimizeParagraphs(content);
        
        // 4. 优化表格
        content = optimizeTables(content);
        
        // 5. 处理列表
        content = optimizeLists(content);
        
        // 6. 清理多余的空标签和换行
        content = cleanupContent(content);
        
        // 7. 添加必要的包装
        content = wrapContent(content);
        
        return content;
    }
    
    /**
     * 移除危险的HTML内容
     */
    private String removeDangerousContent(String content) {
        // 移除script标签
        content = SCRIPT_PATTERN.matcher(content).replaceAll("");
        
        // 移除style标签（我们用CSS统一样式）
        content = STYLE_PATTERN.matcher(content).replaceAll("");
        
        // 移除危险的事件属性
        content = DANGEROUS_ATTRS_PATTERN.matcher(content).replaceAll("");
        
        // 移除潜在的危险标签
        content = content.replaceAll("(?i)<(iframe|embed|object|applet|form|input|button)[^>]*>.*?</\\1>", "");
        
        return content;
    }
    
    /**
     * 优化图片标签
     */
    private String optimizeImages(String content) {
        Matcher matcher = IMG_PATTERN.matcher(content);
        StringBuffer sb = new StringBuffer();
        
        while (matcher.find()) {
            String imgTag = matcher.group(0);
            String imgAttributes = matcher.group(1);
            
            // 提取src属性
            Matcher srcMatcher = SRC_PATTERN.matcher(imgAttributes);
            String src = "";
            if (srcMatcher.find()) {
                src = srcMatcher.group(1);
            }
            
            // 构建优化的图片标签
            String optimizedImg = String.format(
                "<div class=\"image-container\">" +
                "<img src=\"%s\" alt=\"文章图片\" style=\"max-width: 100%%; height: auto; border-radius: 8px;\" " +
                "onerror=\"this.style.display='none'\" loading=\"lazy\">" +
                "</div>", 
                src
            );
            
            matcher.appendReplacement(sb, optimizedImg);
        }
        matcher.appendTail(sb);
        
        return sb.toString();
    }
    
    /**
     * 优化段落和换行
     */
    private String optimizeParagraphs(String content) {
        // 如果内容没有段落标签，按换行分割
        if (!content.contains("<p>") && !content.contains("<div>") && !content.contains("<h")) {
            String[] lines = content.split("\\n");
            StringBuilder sb = new StringBuilder();
            
            for (String line : lines) {
                line = line.trim();
                if (!line.isEmpty()) {
                    sb.append("<p>").append(line).append("</p>");
                }
            }
            content = sb.toString();
        }
        
        // 处理多个连续的br标签
        content = MULTI_BR_PATTERN.matcher(content).replaceAll("<br><br>");
        
        return content;
    }
    
    /**
     * 优化表格
     */
    private String optimizeTables(String content) {
        // 为表格添加响应式包装
        content = content.replaceAll("(?i)<table([^>]*)>", 
            "<div class=\"table-container\" style=\"overflow-x: auto; margin: 16px 0;\">" +
            "<table$1 style=\"width: 100%; border-collapse: collapse; font-size: 14px;\">");
        
        content = content.replaceAll("(?i)</table>", "</table></div>");
        
        // 优化表格单元格
        content = content.replaceAll("(?i)<(th|td)([^>]*)>", 
            "<$1$2 style=\"border: 1px solid #ddd; padding: 8px; text-align: left;\">");
        
        return content;
    }
    
    /**
     * 优化列表
     */
    private String optimizeLists(String content) {
        // 为列表添加样式
        content = content.replaceAll("(?i)<(ul|ol)([^>]*)>", 
            "<$1$2 style=\"margin: 16px 0; padding-left: 24px;\">");
        
        content = content.replaceAll("(?i)<li([^>]*)>", 
            "<li$1 style=\"margin: 8px 0; line-height: 1.6;\">");
        
        return content;
    }
    
    /**
     * 清理多余的内容
     */
    private String cleanupContent(String content) {
        // 移除空的段落和div
        content = EMPTY_TAGS_PATTERN.matcher(content).replaceAll("");
        
        // 移除多余的空白字符
        content = content.replaceAll("\\s+", " ");
        
        // 移除标签间的多余空白
        content = content.replaceAll(">\\s+<", "><");
        
        return content.trim();
    }
    
    /**
     * 添加内容包装
     */
    private String wrapContent(String content) {
        // 如果内容很短且没有块级元素，用段落包装
        if (content.length() < 100 && !content.contains("<div>") && 
            !content.contains("<p>") && !content.contains("<h")) {
            content = "<p>" + content + "</p>";
        }
        
        return content;
    }
    
    /**
     * 提取纯文本内容（用于摘要生成）
     */
    public String extractPlainText(String htmlContent) {
        if (htmlContent == null || htmlContent.isEmpty()) {
            return "";
        }
        
        String text = htmlContent;
        
        // 移除所有HTML标签
        text = text.replaceAll("<[^>]+>", "");
        
        // 解码HTML实体
        text = text.replace("&nbsp;", " ");
        text = text.replace("&amp;", "&");
        text = text.replace("&lt;", "<");
        text = text.replace("&gt;", ">");
        text = text.replace("&quot;", "\"");
        text = text.replace("&apos;", "'");
        
        // 清理多余的空白
        text = text.replaceAll("\\s+", " ");
        
        return text.trim();
    }
    
    /**
     * 生成文章摘要
     */
    public String generateSummary(String htmlContent, int maxLength) {
        String plainText = extractPlainText(htmlContent);
        
        if (plainText.length() <= maxLength) {
            return plainText;
        }
        
        // 尝试在句号处截断
        String summary = plainText.substring(0, maxLength);
        int lastDot = summary.lastIndexOf('。');
        if (lastDot > maxLength * 0.7) {
            summary = summary.substring(0, lastDot + 1);
        } else {
            summary = summary + "...";
        }
        
        return summary;
    }
    
    /**
     * 验证HTML内容是否安全
     */
    public boolean isContentSafe(String htmlContent) {
        if (htmlContent == null) return true;
        
        // 检查是否包含危险标签
        String[] dangerousTags = {"script", "iframe", "object", "embed", "form", "input"};
        for (String tag : dangerousTags) {
            if (htmlContent.toLowerCase().contains("<" + tag)) {
                return false;
            }
        }
        
        // 检查是否包含危险属性
        if (DANGEROUS_ATTRS_PATTERN.matcher(htmlContent).find()) {
            return false;
        }
        
        return true;
    }
}